<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <!-- bootstrap -->
    <link rel="stylesheet" href="./bootstrap/css/bootstrap.min.css" />
    <script src="./bootstrap/js/bootstrap.min.js"></script>

    <!-- fontawesome -->
    <link rel="stylesheet" href="./fontawesome/css/all.min.css" />
    <script src="./fontawesome/js/all.min.js"></script>
  </head>
  <body>
    <div class="card m-2">
      <div class="card-header">筛选</div>
      <div class="card-body">
        <form class="row g-2" name="filterUsersForm">
          <div class="col-4">
            <div class="input-group input-group-sm">
              <span class="input-group-text">用户</span>
              <input type="text" name="username" class="form-control" />
            </div>
          </div>
          <div class="col-4">
            <div class="input-group input-group-sm">
              <span class="input-group-text">姓名</span>
              <input type="text" name="name" class="form-control" />
            </div>
          </div>
          <div class="col-4">
            <div class="input-group input-group-sm">
              <span class="input-group-text">邮箱</span>
              <input type="text" name="email" class="form-control" />
            </div>
          </div>

          <div class="col-4">
            <div class="input-group input-group-sm">
              <span class="input-group-text">手机</span>
              <input type="text" name="phone" class="form-control" />
            </div>
          </div>
          <div class="col-4">
            <button
              data-action="filterUsersList"
              class="btn btn-primary btn-sm"
              type="button"
            >
              筛选
            </button>
          </div>
        </form>
      </div>
    </div>

    <div class="bg-body-tertiary p-2">
      <button data-action="addUser" class="btn btn-primary btn-sm">添加</button>
      <button disabled data-action="deleteUsers" class="btn btn-danger btn-sm">
        删除
      </button>
    </div>

    <div id="usersList"></div>

    <div id="pagination"></div>
    <script type="module">
      import {
        _on,
        _confirm,
        _dialog,
        _validForm,
        _pagination,
      } from "./utils/functions.js";
      import { getUsersList, addDialog, editDialog } from "./js/users.js";
      import { departmentsTreeRadioList } from "./js/departments.js";

      import PocketBase from "./pocketbase.es.js";

      const pb = new PocketBase("http://127.0.0.1:8090");

      //---
      const html = String.raw;

      getUsersList();

      const deleteUsersBtn = document.querySelector(
        '[data-action="deleteUsers"]'
      );

      _on("change", {
        editAvatarUpload() {
          const file = this.files[0];
          const url = URL.createObjectURL(file);
          editAvatarThumb.src = url;
        },
        addAvatarUpload() {
          const file = this.files[0];
          const url = URL.createObjectURL(file);
          addAvatarThumb.src = url;
        },
        checkAll() {
          const rows = [
            ...document.querySelectorAll('[data-action="checkRow"]'),
          ];
          rows.forEach((el) => (el.checked = this.checked));
          // 控制删除是否可以用
          deleteUsersBtn.disabled = this.checked === false;
        },
        checkRow() {
          const rows = [
            ...document.querySelectorAll('[data-action="checkRow"]'),
          ];
          // document.querySelectorAll('[data-action="checkRow"]:checked')
          const rowsCount = rows.length;
          const checkRowsCount = rows.filter((el) => el.checked).length;

          const checkAll = document.querySelector('[  data-action="checkAll"]');
          checkAll.checked = rowsCount === checkRowsCount;

          // 控制删除是否可以用
          deleteUsersBtn.disabled = checkRowsCount === 0;
        },
      });

      _on("input", {
        editValid() {
          /* username */
          if (this.name === "username") {
            _validForm(this, () => /^\w{3,18}$/.test(this.value));
          }
          /* password */
          if (this.name === "password") {
            _validForm(this, () => /^.{8,}$/.test(this.value));
          }
          /* passwordConfirm */
          if (this.name === "passwordConfirm") {
            _validForm(this, (value) => value === addForm.password.value);
          }
          /* email */
          if (this.name === "email") {
            _validForm(this, () =>
              /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(
                this.value
              )
            );
          }
          /* name */
          if (this.name === "name") {
            _validForm(this, () => /^.{2,18}$/.test(this.value));
          }
          /* phone */
          if (this.name === "phone") {
            _validForm(this, () =>
              /^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(this.value)
            );
          }
          /* age */

          if (this.name === "age") {
            _validForm(this, () => +this.value >= 18 && +this.value <= 100);
          }
        },

        valid() {
          /* username */
          if (this.name === "username") {
            _validForm(this, () => /^\w{3,18}$/.test(this.value));
          }
          /* password */
          if (this.name === "password") {
            _validForm(this, () => /^.{8,}$/.test(this.value));
          }
          /* passwordConfirm */
          if (this.name === "passwordConfirm") {
            _validForm(this, (value) => value === addForm.password.value);
          }
          /* email */
          if (this.name === "email") {
            _validForm(this, () =>
              /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(
                this.value
              )
            );
          }
          /* name */
          if (this.name === "name") {
            _validForm(this, () => /^.{2,18}$/.test(this.value));
          }
          /* phone */
          if (this.name === "phone") {
            _validForm(this, () =>
              /^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(this.value)
            );
          }
          /* age */

          if (this.name === "age") {
            _validForm(this, () => +this.value >= 18 && +this.value <= 100);
          }
        },
      });

      _on("click", {
        /* 筛选用户 */
        filterUsersList() {
          // 1 获取表单数据
          const fd = new FormData(document.filterUsersForm);
          // 2 将fd转换为字符串
          let filterStr = "";
          [...fd.entries()].forEach(([k, v]) => {
            if (v !== "") {
              filterStr += `${k}~'${v}'&&`;
            }
          });
          filterStr = filterStr.slice(0, -2);

          //持久化存储筛选条件
          // localStorage.usersTableFilter = filterStr;
          window.usersTableFilter = filterStr;
          getUsersList();
        },
        /* 点击分页
          1. 响应用户点击事件
          2. 点击后获取分页数字
        */
        changePage() {
          // console.log(this.dataset.page);
          localStorage.usersTablePage = this.dataset.page;
          getUsersList();
        },
        async editSaveUser() {
          const form = document.editForm;
          /* username */
          const v1 = _validForm(form.username, (value) =>
            /^\w{3,18}$/.test(value)
          );
          /* email */
          const v2 = _validForm(form.email, (value) =>
            /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(
              value
            )
          );
          /* name */
          const v3 = _validForm(form.name, (value) => /^.{2,18}$/.test(value));
          /* phone */
          const v4 = _validForm(form.phone, (value) =>
            /^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(value)
          );
          /* age */
          const v5 = _validForm(
            form.age,
            (value) => +value >= 18 && +value <= 100
          );

          if ((v1 && v2 && v3 && v4 && v5) === false) return;

          // 获取表单数据
          // const data = {};
          // data.username = form.username.value;
          // data.email = form.email.value;
          // data.name = form.name.value;
          // data.age = form.age.value;
          // data.gender = form.gender.value;
          // data.phone = form.phone.value;
          // data.department = form.pid.value;
          const id = form.id.value;
          const fd = new FormData(form);
          fd.delete("id");
          if (fd.get("avatar").size === 0) fd.delete("avatar");

          try {
            await pb.collection("users").update(id, fd);
            editDialog.hide();
            getUsersList();
          } catch (error) {
            console.log(error.message);
          }
        },

        async addSaveUser() {
          const form = document.addForm;
          /* username */
          const v1 = _validForm(form.username, (value) =>
            /^\w{3,18}$/.test(value)
          );
          /* email */
          const v2 = _validForm(form.email, (value) =>
            /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(
              value
            )
          );
          /* name */
          const v3 = _validForm(form.name, (value) => /^.{2,18}$/.test(value));
          /* phone */
          const v4 = _validForm(form.phone, (value) =>
            /^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(value)
          );
          /* age */
          const v5 = _validForm(
            form.age,
            (value) => +value >= 18 && +value <= 100
          );
          /* password */
          const v6 = _validForm(form.password, (value) =>
            /^.{8,}$/.test(value)
          );
          const v7 = _validForm(
            form.passwordConfirm,
            (value) => value === form.password.value
          );

          if ((v1 && v2 && v3 && v4 && v5 && v6 && v7) === false) return;

          // 获取表单数据
          // const data = {};
          // data.emailVisibility = true;
          // data.username = form.username.value;
          // data.password = form.password.value;
          // data.passwordConfirm = form.passwordConfirm.value;
          // data.email = form.email.value;
          // data.name = form.name.value;
          // data.age = form.age.value;
          // data.gender = form.gender.value;
          // data.phone = form.phone.value;
          // data.department = form.pid.value;
          // http://127.0.0.1:8090/api/files/COLLECTION_ID_OR_NAME/RECORD_ID/FILENAME
          // http://127.0.0.1:8090/api/files/users/kyuw2szzyxgt9c5/animation_96px_lLY479lpA7.png

          // http://127.0.0.1:8090/api/files/_pb_users_auth_/kyuw2szzyxgt9c5/agent_smith_96px_DeoC5MUq8z.png?thumb=100x100

          // pb.files.getUrl(record, firstFilename);

          const fd = new FormData(form);
          fd.append("emailVisibility", true);
          try {
            await pb.collection("users").create(fd);
            addDialog.hide();
            getUsersList();
          } catch (error) {
            console.log(error.message);
          }
        },

        cancelAddSaveUser() {
          addDialog.hide();
        },
        /* 添加用户 */
        async addUser() {
          addDialog.show();

          // 生成部门列表
          const records = await pb.collection("departments").getFullList({
            sort: "-sort",
          });
          addPidRadioList.innerHTML = departmentsTreeRadioList(records);
        },
        async editUser() {
          editDialog.show();
          const id = this.dataset.id;
          const form = document.editForm;
          // 回填数据
          try {
            const record = await pb.collection("users").getOne(id);

            form.id.value = record.id;
            form.username.value = record.username;
            form.email.value = record.email;
            form.name.value = record.name;
            form.age.value = record.age;
            form.gender.value = record.gender;
            form.phone.value = record.phone;

            if (record.avatar)
              editAvatarThumb.src = `http://127.0.0.1:8090/api/files/_pb_users_auth_/${record.id}/${record.avatar}`;

            // 生成部门列表
            const records = await pb.collection("departments").getFullList({
              sort: "-sort",
            });
            editPidRadioList.innerHTML = departmentsTreeRadioList(records);

            form.pid.value = record.department;
          } catch (error) {}
        },
        async cancelEditSaveUser() {
          editDialog.hide();
        },

        // 删除
        async deleteUsers() {
          if ((await _confirm("删除", "确定删除吗")) === false) return;
          try {
            const ids = [
              ...document.querySelectorAll('[data-action="checkRow"]:checked'),
            ].map((el) => pb.collection("users").delete(el.dataset.id));
            //等待所有的promise执行完毕，无论对错
            await Promise.allSettled(ids);
            editDialog.hide();
            getUsersList();
          } catch (error) {}
        },
        async deleteUser() {
          const id = this.dataset.id;
          if ((await _confirm("删除", "确定删除吗")) === false) return;
          try {
            await pb.collection("users").delete(id);
            getUsersList();
          } catch (error) {}
        },
      });
    </script>
  </body>
</html>
